package cn.lili.header;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * feign request 拦截
 *
 * @author Chopper
 * @version v1.0
 * 2022-09-07 14:29
 */
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        Map<String, String> headers = getHeaders();
        headers.forEach(template::header);
    }

    /**
     * 获取 request 中的所有的 header 值
     *
     * @return
     */
    private Map<String, String> getHeaders() {
        Map<String, String> map = new LinkedHashMap<>();
        if (RequestContextHolder.getRequestAttributes() != null) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String key = headerNames.nextElement();
                String value = request.getHeader(key);
                // 跳过 content-length，解决too many bites written的问题
                if (key.equalsIgnoreCase("content-length")) {
                    continue;
                }
                map.put(key, value);
            }
        }
        return map;
    }
}